ANDROID | 动态权限

在Android6.0及以上版本中,即使在AndroidManifest.xml文件里配置了如下权限:

1
<uses-permission android:name="android.permission.CALL_PHONE"/>

运行时会也会报错:
java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{ece7708 3894:com.test.xianxiaotao.test/u0a79} (pid=3894, uid=10079) with revoked permission android.permission.CALL_PHONE

这是因为Android6.0及以上版本增添了动态权限。在哪个页面需要这个权限只需要直接去请求就行了,而且还有了相应的监听的方法供你来判断。具体使用参考如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 动态请求权限
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 0x11);
editText = (EditText) findViewById(R.id.editText);
}
/**
* 拨打
* @param v 触发监听事件的view
*/
public void call(View v) {
String number = editText.getText().toString();
if (null == number || number.length() == 0)
return;
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel://" + number));
startActivity(intent);
}
/**
* 监听权限是否允许
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 0x11) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Log.i("CMCC", "权限被允许");
else
Log.i("CMCC", "权限被拒绝");
}
}
}

运行结果:

使用权限的页面中弹出提示框并被允许,则以后不再弹出。